package com.li.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.li.constant.MessageConstant;
import com.li.entity.Result;
import com.li.service.MemberService;
import com.li.service.ReportService;
import com.li.service.SetmealService;
import com.li.utils.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    MemberService memberService;
    @Reference
    ReportService reportService;
    @Reference
    SetmealService setmealService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport(String date) throws Exception {
//        System.out.println("date = " + date);

        //第一次加载的时候date数据为空
        if ("".equals(date) || date == null) {
            HashMap<String, Object> map = new HashMap<>();
            //获取过去一年的每个月
            ArrayList<String> month = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();

            calendar.add(calendar.MONTH, -12);
            for (int i = 0; i < 12; i++) {
                calendar.add(calendar.MONTH, 1);
                month.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }
            map.put("months", month);

            //获取每个月截止的会员人数
            List<Integer> memberCount = memberService.findMemberCountByMonth(month);
            map.put("memberCount", memberCount);

            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } else {
            //带有数据时查询
            String[] dates = date.split(",");
            String start = dates[0];
//            System.out.println("start = " + start);
            String end = dates[1];
//            System.out.println("end = " + end);
            Date startDate = DateUtils.parseString2Date(start, "yyyy-MM");
            System.out.println("startDate = " + startDate);
            Date endDate = DateUtils.parseString2Date(end, "yyyy-MM");
            System.out.println("endDate = " + endDate);

            //计算两个日期之间所差的月份
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(startDate);
            c2.setTime(endDate);
            int year1 = c1.get(Calendar.YEAR);
            int year2 = c2.get(Calendar.YEAR);
            int month1 = c1.get(Calendar.MONTH);
            int month2 = c2.get(Calendar.MONTH);
            int day1 = c1.get(Calendar.DAY_OF_MONTH);
            int day2 = c2.get(Calendar.DAY_OF_MONTH);
            // 获取年的差值 
            int yearInterval = year1 - year2;
            // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
            if (month1 < month2 || month1 == month2 && day1 < day2) {
                yearInterval--;
            }
            // 获取月数差值
            int monthInterval = (month1 + 12) - month2;
            if (day1 < day2) {
                monthInterval--;
            }
            monthInterval %= 12;
            int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
            System.out.println("monthsDiff = " + monthsDiff);


            HashMap<String, Object> map = new HashMap<>();
            //获取时间段内的每个月
            ArrayList<String> month = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            calendar.add(calendar.MONTH, -monthsDiff - 1);
            for (int i = 0; i <= monthsDiff; i++) {
                calendar.add(calendar.MONTH, 1);
                month.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }
            map.put("months", month);

        /*    for (String s : month) {
                System.out.println("s = " + s);
            }*/
            //获取每个月截止的会员人数
            List<Integer> memberCount = memberService.findMemberCountByMonth(month);
            map.put("memberCount", memberCount);

            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);

        }

    }


    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {

        try {
            //获取套餐名与套餐数 setmealCount setmealNames
            List<Map<String, Object>> setmelCount = setmealService.findSetmelCount();

            HashMap<String, Object> map = new HashMap<>();
            map.put("setmealCount", setmelCount);

            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> setmeal : setmelCount) {
                setmealNames.add((String) setmeal.get("name"));
            }

            map.put("setmealNames", setmealNames);
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //男女会员占比
    @RequestMapping("/getMemberSex")
    public Result getMemberSex() {
        Map<String, Object> map = new HashMap<>();
        try {
            List<Map<String, Object>> list = memberService.findMemberBySex();
            map.put("sexCount", list);
            List<String> memberSex = new ArrayList<>();
            if (list != null && list.size() > 0) {
                for (Map<String, Object> m : list) {
                    if (m.get("name") == null) {
                        m.put("name", "性别未知");
                    } else if (m.get("name").equals("1")) {
                        m.put("name", "男");
                    } else if (m.get("name").equals("2")) {
                        m.put("name", "女");
                    }
                    String name = (String) m.get("name");
                    memberSex.add(name);
                }
            }
            map.put("memberSex", memberSex);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //会员年龄段占比
    @RequestMapping("/getMemberAge")
    public Result getMemberAge() {
        HashMap<String, Object> data = new HashMap<>();
        List<Map> mapList = new ArrayList<>();
        try {
            List<String> memberAge = new ArrayList<>();
            String begin = "";
            String end = "";
            Calendar calendar = Calendar.getInstance();

            //当前时间
            String yearnow = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

            //18年前
            calendar.add(calendar.YEAR, -18);
            String year18ago = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
            end = yearnow;
            begin = year18ago;
            List<Map<String, Object>> list = memberService.findMemberByAge(begin, end);
            if (list != null && list.size() > 0) {
                for (Map<String, Object> map : list) {
                    Long value = (Long) map.get("value");
                    if (value == 0 || value == null) {
                        break;
                    }
                    map.put("name", "0-18岁");
                    String name = (String) map.get("name");
                    memberAge.add(name);
                    mapList.add(map);
                }
            }

            //30年前
            String begin1 = "";
            String end1 = "";
            calendar.add(calendar.YEAR, -12);
            String year30ago = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
            begin1 = year30ago;
            end1 = year18ago;
            List<Map<String, Object>> list1 = memberService.findMemberByAge(begin1, end1);
            if (list1 != null && list1.size() > 0) {
                for (Map<String, Object> map : list1) {
                    Long value = (Long) map.get("value");
                    if (value == 0 || value == null) {
                        break;
                    }
                    map.put("name", "18-30岁");
                    String name = (String) map.get("name");
                    memberAge.add(name);
                    mapList.add(map);
                }
            }

            //45年前
            String begin2 = "";
            String end2 = "";
            calendar.add(calendar.YEAR, -15);
            String year45ago = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
            begin2 = year45ago;
            end2 = year30ago;
            List<Map<String, Object>> list2 = memberService.findMemberByAge(begin2, end2);
            if (list2 != null && list1.size() > 0) {
                for (Map<String, Object> map : list2) {
                    Long value = (Long) map.get("value");
                    if (value == 0 || value == null) {
                        break;
                    }
                    map.put("name", "30-45岁");
                    String name = (String) map.get("name");
                    memberAge.add(name);
                    mapList.add(map);
                }
            }
            //大于45岁
            String begin3 = "";
            String end3 = "";
            calendar.add(calendar.YEAR, -150);
            String year45after = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
            end3 = year45ago;
            begin3 = year45after;
            List<Map<String, Object>> list3 = memberService.findMemberByAge(begin3, end3);
            if (list3 != null && list1.size() > 0) {
                for (Map<String, Object> map : list3) {
                    Long value = (Long) map.get("value");
                    if (value == 0 || value == null) {
                        break;
                    }
                    map.put("name", "大于45岁");
                    String name = (String) map.get("name");
                    memberAge.add(name);
                    mapList.add(map);
                }
            }
            data.put("memberage", memberAge);
            data.put("ageCount", mapList);

            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        //获取运营统计数据
        try {
            Map<String, Object> map = reportService.getBusinessReport();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {

        try {
            //远程调用报表服务获取报表数据
            Map<String, Object> result = reportService.getBusinessReport();

            //取出返回结果数据 将报表数据写入到excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //获取模板文件
            String templateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //生成模板文件
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
            //获取工作表
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取工作行
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);
            //设置第5行数据
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);
            //设置第6行数据
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);
            //设置第8行数据
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);
            //设置第9行数据
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);
            //设置第10行数据
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);
            //13行开始
            int rowStart = 12;
            for (Map map : hotSetmeal) {
                BigDecimal bigDecimal = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowStart++);
                row.getCell(4).setCellValue((String) map.get("name"));
                row.getCell(5).setCellValue((Long) map.get("setmeal_count"));
                row.getCell(6).setCellValue(bigDecimal.doubleValue());
            }

            //设置响应mime类型
            response.setContentType("application/vnd.ms-excel");
            //以附件形式进行下载
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();

            workbook.write(out);
            out.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "未知错误");
        }
    }

    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {

        try {
            //远程调用报表服务获取报表数据
            Map<String, Object> result = reportService.getBusinessReport();


            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //获取模板文件
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            //填充数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, result, new JRBeanCollectionDataSource(hotSetmeal));

            //通过输出流进行下载
            ServletOutputStream out = response.getOutputStream();
            //设置响应mime类型
            response.setContentType("application/pdf");
            //以附件形式进行下载
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //导出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint, out);

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "未知错误");
        }
    }

}

